import axios from 'axios'
import {message, Modal, notification} from 'ant-design-vue'
import moment from 'moment'
import store from '../store'
import db from 'utils/localstorage'
import qs from 'qs'

moment.locale('zh-cn')

// 统一配置
let REDP_REQUEST = axios.create({
  // 前后端分离部署时使用固定URL：baseURL: 'http://localhost:9527/'
  // 前后端相同容器部署（前后端端口都相同）时，可直接使用：baseURL: window.location.origin
  // 前后端相同机器部署（前后端端口号不同）时，使用以下：
  // baseURL: window.location.origin.replace(/:(\d{1,5})/, ':9527'),
  // baseURL: 'http://10.90.0.19:9527/',
  // baseURL: 'http://10.10.10.18:9527/',
  // baseURL: 'http://127.0.0.1:9527/',
  // baseURL: window.location.origin+"/UPMP/DEV/",
  // baseURL: 'http://127.0.0.1:20117/UPMP/DEV/',

  // baseURL: 'http://127.0.0.1:10010/UPMP/DEV/',
  baseURL: 'http://172.17.100.9:62126/UPMP/DEV/',
  // baseURL: 'http://10.147.17.66:20117/UPMP/DEV/',
  // baseURL: 'http://igas.rengu.cc:12107/UPMPTEST/',
  // baseURL: 'http://59.110.215.135:12147/UPMPTEST',
  // baseURL: 'http://59.110.215.135:12147',
  responseType: 'json',
  validateStatus (status) {
    // 200 外的状态码都认定为失败
    return status === 200
  }
})

// 拦截请求
REDP_REQUEST.interceptors.request.use((config) => {
  let expireTime = store.state.account.expireTime
  let now = moment().format('YYYYMMDDHHmmss')
  // 让token早10秒种过期，提升“请重新登录”弹窗体验
  if (now - expireTime >= -10) {
    Modal.error({
      title: '登录已过期',
      content: '很抱歉，登录已过期，请重新登录',
      okText: '重新登录',
      mask: false,
      onOk: () => {
        return new Promise((resolve, reject) => {
          db.clear()
          location.reload()
        }).catch(function (reason) {
          console.log('catch:', reason)
        })
      }
    })
  }
  // 有 token就带上
  if (store.state.account.token) {
    config.headers.Authentication = store.state.account.token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 拦截响应
REDP_REQUEST.interceptors.response.use((rsp) => {
  // 更新令牌信息
  if (rsp.headers['token-update'] !== undefined && rsp.headers['token-exp-update'] !== undefined) {
    store.commit('account/setToken', rsp.headers['token-update'])
    store.commit('account/setExpireTime', rsp.headers['token-exp-update'])
  }
  return rsp
}, (error) => {
  if (error.response) {
    let errorMessage = error.response.data === null ? '系统内部异常，请联系网站管理员' : error.response.data.message
    switch (error.response.status) {
      case 404:
        notification.error({
          message: '系统提示',
          description: '很抱歉，资源未找到',
          duration: 4
        })
        break
      case 403:
      case 401:
        notification.warn({
          message: '系统提示',
          description: '很抱歉，您无法访问该资源，可能是因为没有相应权限或者登录已失效',
          duration: 4,
          btn: h => {
            return h(
              'a-button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: () => {
                    return new Promise((resolve, reject) => {
                      db.clear()
                      location.reload()
                    })
                  }
                }
              },
              '重新登陆'
            )
          }
        })
        break
      default:
        notification.error({
          message: '系统提示',
          description: errorMessage,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
})

const request = {
  // 处理json格式的post请求
  postJson (url, params) {
    return REDP_REQUEST.post(url, params, {
      headers: {
        'Content-Type': 'text/plain'
      },
      data: params
    })
  },
  post (url, params) {
    return REDP_REQUEST.post(url, params, {
      transformRequest: [
        params => qs.stringify(params, {
          allowDots: true
        })
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  put (url, params) {
    return REDP_REQUEST.put(url, params, {
      transformRequest: [
        params => qs.stringify(params, {
          allowDots: true
        })
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  get (url, params) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (let key in params) {
        if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== undefined) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    if (_params.length > 0 && _params.lastIndexOf('&') === _params.length - 1) {
      _params = _params.substr(0, _params.length - 1)
    }
    return REDP_REQUEST.get(`${url}${_params}`)
  },
  delete (url, params) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (let key in params) {
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    if (_params.length > 0 && _params.lastIndexOf('&') === _params.length - 1) {
      _params = _params.substr(0, _params.length - 1)
    }
    return REDP_REQUEST.delete(`${url}${_params}`)
  },
  export (url, params = {}) {
    message.loading('导出数据中')
    return REDP_REQUEST.post(url, params, {
      transformRequest: [(params) => {
        let result = ''
        Object.keys(params).forEach((key) => {
          if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
            result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
          }
        })
        if (result.length > 0 && result.lastIndexOf('&') === result.length - 1) {
          result = result.substr(0, result.length - 1)
        }
        return result
      }],
      responseType: 'blob'
    }).then((r) => {
      const content = r.data
      const blob = new Blob([content])
      let fileName = `${new Date().getTime()}_导出结果.xlsx`
      if(r.headers && r.headers["file-name"]){
        fileName = decodeURIComponent(r.headers["file-name"])+'.xlsx';
      }
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch((r) => {
      console.error(r)
      message.error('导出失败')
    })
  },
  download (url, params, filename) {
    message.loading('文件传输中')
    return REDP_REQUEST.post(url, params, {
      transformRequest: [(params) => {
        let result = ''
        Object.keys(params).forEach((key) => {
          if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
            result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
          }
        })
        if (result.length > 0 && result.lastIndexOf('&') === result.length - 1) {
          result = result.substr(0, result.length - 1)
        }
        return result
      }],
      responseType: 'blob'
    }).then((r) => {
      const content = r.data
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = filename
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, filename)
      }
    }).catch((r) => {
      console.error(r)
      message.error('下载失败')
    })
  },
  upload (url, params) {
    return REDP_REQUEST.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  send (options) {
    return REDP_REQUEST(options)
  }
}

export default request
